package com.btpj.module_main.ui.home

import androidx.lifecycle.viewModelScope
import androidx.paging.DataSource
import androidx.paging.PageKeyedDataSource
import com.btpj.jetpack.base.BaseListViewModel
import com.btpj.jetpack.entity.DataBean
import com.btpj.jetpack.utils.ToastUtil
import com.btpj.jetpack.entity.ApiResult
import com.btpj.module_main.data.remote.repository.MainRepository
import kotlinx.coroutines.launch
import java.util.*

class HomeListViewModel(private val repository: MainRepository) : BaseListViewModel<DataBean>() {
    override fun createDataSource(): DataSource<Int, DataBean> {
        return object : PageKeyedDataSource<Int, DataBean>() {
            override fun loadInitial(
                params: LoadInitialParams<Int>,
                callback: LoadInitialCallback<Int, DataBean>
            ) {
                getHomeList(0, callback)
            }

            override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, DataBean>) {
                getHomeList(params.key, params.key + 1, callback)
            }

            override fun loadBefore(
                params: LoadParams<Int>,
                callback: LoadCallback<Int, DataBean>
            ) {
                callback.onResult(Collections.emptyList(), null)
            }
        }
    }

    private fun getHomeList(
        count: Int,
        callback: PageKeyedDataSource.LoadInitialCallback<Int, DataBean>
    ) {
        viewModelScope.launch {
            when (val result = repository.getHomeList(count)) {
                is ApiResult.Success -> callback.onResult(result.data.datas, null, 1)
                is ApiResult.Error -> ToastUtil.showShort(
                    result.exception.errorMsg ?: "请求失败"
                )
            }
        }
    }

    fun getHomeList(
        count: Int,
        key: Int,
        callback: PageKeyedDataSource.LoadCallback<Int, DataBean>
    ) {
        viewModelScope.launch {
            when (val result = repository.getHomeList(count)) {
                is ApiResult.Success -> callback.onResult(result.data.datas, key)
                is ApiResult.Error -> ToastUtil.showShort(
                    result.exception.errorMsg ?: "请求失败"
                )
            }
        }
    }
}